# -*- coding: utf-8 -*-

from server.controller import user
from server.controller import session
from server.controller import request
from server.controller import userDao
from server.controller import datetime
from server.controller import json


userObj = userDao()


@user.route('/session')
def get_session():
    response = {}
    data = {}

    if 'user' not in session:
        response['code'] = 1001
        response['msg'] = ""
        response['data'] = data
    else:
        response['code'] = 0
        response['msg'] = ""
        response['data'] = session.get('user')

    return response


@user.route('/logout')
def logout():
    response = {}
    data = {}

    session.pop('user')

    response['code'] = 0
    response['msg'] = "退出成功"
    response['data'] = data

    return response


@user.route('/login')
def login():
    response = {}
    data = {}

    username = request.args.get('username')
    password = request.args.get('password')

    userSession = userObj.login(username, password)
    if userSession is not None:
        userSession.pop('_id')
        session['user'] = userSession

        response['code'] = 0
        response['msg'] = "登入成功"
        response['data'] = data
    else:
        response['code'] = 1
        response['msg'] = "登入失败"
        response['data'] = data

    return response


@user.route('/getInfo')
def get_info():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        info = userObj.select_info(userSession)
        if info is None:
            response['code'] = 1
            response['msg'] = "操作失败"
            response['data'] = data
        else:
            response['code'] = 0
            response['msg'] = "查询成功"
            response['data'] = info

    return response


@user.route('/setInfo')
def set_info():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        info = {"nickname": request.args.get('nickname'),
                "sex": request.args.get('sex'),
                "email": request.args.get('email'),
                "remarks": request.args.get('remarks')}

        nowSession = userObj.update_info(userSession, info)
        if nowSession is None:
            response['code'] = 1
            response['msg'] = "操作失败"
            response['data'] = data
        else:
            session['user'] = nowSession
            response['code'] = 0
            response['msg'] = "修改成功"
            response['data'] = data

    return response


@user.route('/setPassword')
def set_password():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        ret = userObj.update_password(userSession,
                                      request.args.get('oldPassword'),
                                      request.args.get('password'))
        if not ret:
            response['code'] = 1
            response['msg'] = "操作失败"
            response['data'] = data
        else:
            response['code'] = 0
            response['msg'] = "修改成功"
            response['data'] = data

    return response


@user.route('/getUsers')
def get_users():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        if userSession['role'] != '1':
            response['code'] = 1
            response['msg'] = "用户权限不足"
            response['data'] = data
        else:
            condition = {"username": request.args.get('username'),
                         "role": request.args.get('role')}

            if condition['username'] == '' or condition['username'] is None:
                condition.pop('username')

            if condition['role'] == '0' or condition['role'] is None:
                condition.pop('role')

            limit = {"page": int(request.args.get('page')),
                     "limit": int(request.args.get('limit'))}

            count, data = userObj.select_users(userSession, condition, limit)

            if count == 0:
                response['code'] = 1
                response['msg'] = "无数据"
                response['data'] = data
            else:
                response['code'] = 0
                response['msg'] = "查询成功"
                response['count'] = count
                response['data'] = data

    return response


@user.route('/addUser')
def add_user():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        if userSession['role'] != '1':
            response['code'] = 1
            response['msg'] = "用户权限不足"
            response['data'] = data
        else:
            userInfo = {"username": request.args.get('username'),
                        "password": "123456",
                        "nickname": request.args.get('nickname'),
                        "sex": request.args.get('sex'),
                        "email": request.args.get('email'),
                        "createDate": datetime.datetime.now().strftime('%Y-%m-%d'),
                        "remarks": "",
                        "role": request.args.get('role')}

            if userInfo['username'] == "" or userInfo['role'] == "0":
                response['code'] = 1
                response['msg'] = "创建用户需填写用户名和角色"
                response['data'] = data
            else:
                ret = userObj.add_user(userSession, userInfo)

                if not ret:
                    response['code'] = 1
                    response['msg'] = "添加用户失败"
                    response['data'] = data
                else:
                    response['code'] = 0
                    response['msg'] = "添加用户成功"
                    response['data'] = {"password": userInfo['password']}

    return response


@user.route('/deleteUser', methods=['POST'])
def delete_user():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        if userSession['role'] != '1':
            response['code'] = 1
            response['msg'] = "用户权限不足"
            response['data'] = data
        else:
            username = userSession['username']
            password = request.form.get('password')

            userRet = userObj.login(username, password)
            if userRet is None:
                response['code'] = 100
                response['msg'] = "管理员密码错误"
                response['data'] = data
            else:
                ret = True
                users = request.form.get('batchData')
                for username in json.loads(users):
                    if not userObj.delete_user(userSession, {"username": username}):
                        data.append({"username": username})
                        ret = False

                if not ret:
                    response['code'] = 1
                    response['msg'] = "删除用户失败"
                    response['data'] = data
                else:
                    response['code'] = 0
                    response['msg'] = "删除用户成功"
                    response['data'] = data

    return response


@user.route('/resetPassword')
def reset_password():
    response = {}
    data = {}

    userSession = session.get('user')
    if userSession is None:
        response['code'] = 1
        response['msg'] = "用户未登录"
        response['data'] = data
    else:
        if userSession['role'] != '1':
            response['code'] = 1
            response['msg'] = "用户权限不足"
            response['data'] = data
        else:
            username = userSession['username']
            password = request.args.get('password')

            userRet = userObj.login(username, password)
            if userRet is None:
                response['code'] = 100
                response['msg'] = "管理员密码错误"
                response['data'] = data
            else:
                resetUser = request.args.get('resetUser')
                ret = userObj.reset_user_password(userSession, resetUser)

                if not ret:
                    response['code'] = 1
                    response['msg'] = "重置用户密码失败"
                    response['data'] = data
                else:
                    response['code'] = 0
                    response['msg'] = "重置用户密码成功"
                    response['data'] = {"password": "123456"}

    return response
